//
//  LSLevinBookListViewController.m
//  LaSaCivilAffairsDepartment
//
//  Created by 聂志康 on 2019/8/20.
//  Copyright © 2019 wpkj. All rights reserved.
//

#import "LSLevinBookListViewController.h"
#import "LSLevinBookListViewCell.h"
#import "LSLevinBookListModel.h"
#import "LSLevinBookDetailViewController.h"
#import <xlsxwriter/xlsxwriter.h>

#define headerSelectViewHeight 50
#define rows 10

@interface LSLevinBookListViewController () <UITableViewDelegate, UITableViewDataSource, UITextFieldDelegate>
@property (nonatomic, strong) UITextField *selectTF;
@property (nonatomic, strong) UIButton *downSelectButton;
@property (nonatomic, strong) UIButton *searchButton;
@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) NSMutableArray *dataArrayM;
@property (nonatomic, strong) NZKNoDataView *nodataView;
@property (nonatomic, strong) NZKNetworkErrorView *networkErrorView;
@property (nonatomic, strong) NSDictionary *fileClassifyDict;
@property (nonatomic, strong) NSArray *fileClassifyReverseArray;
@property (nonatomic, strong) NSDictionary *fileClassifyReverseDict;
@property (nonatomic, copy) NSString *fileClassifyString;
@property (nonatomic, assign) int page;
@property (nonatomic, strong) UIView *downSelectView;
@property (nonatomic, strong) UIView *downSelectViewBackAlphaView;
@end

static NSString *LSLevinBookListViewCellID = @"LSLevinBookListViewCellID";

@implementation LSLevinBookListViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.title = @"来文登记簿";
    self.fileClassifyString = @"";
    UIButton *exportButton = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 60, 44)];
    [exportButton setTitleColor:UIColor.whiteColor forState:UIControlStateNormal];
    [exportButton setTitle:@"全部导出" forState:UIControlStateNormal];
    exportButton.titleLabel.font = [UIFont systemFontOfSize:14];
    [exportButton addTarget:self action:@selector(createXLSFile) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem *exportButtonItem = [[UIBarButtonItem alloc] initWithCustomView:exportButton];
    self.navigationItem.rightBarButtonItem = exportButtonItem;
    [self.view addSubview:self.tableView];
    [self createHeader];
    self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(loadData)];
}

- (void)viewWillAppear:(BOOL)animated {
    [self loadData];
}

- (void)createXLSFile {
    [self createXLSFileWithArray:self.dataArrayM];
}

- (void)createXLSFileWithArray:(NSArray *)array {
    /*
    NSMutableArray *xlsDataMuArrM = [[NSMutableArray alloc] init];
    for (int i = 0; i < array.count; i ++) {
        LSLevinBookListModel *model = self.dataArrayM[i];
        [xlsDataMuArrM addObject:@{@"文件标题":[ValidateUtils validateNull:model.fileTitle],
                                   @"原文编号":[NSString stringWithFormat:@"‘%@",[ValidateUtils validateNull:model.fileNum]],
                                   @"字号":[ValidateUtils validateNull:model.fileCode],
                                   @"来文单位":[ValidateUtils validateNull:model.fileCompany],
                                   @"收文分类":[ValidateUtils validateNull:[[ValidateUtils validateNull:self.fileClassifyDict[model.fileClassify]] isEqualToString:@""] ? model.fileClassify : self.fileClassifyDict[model.fileClassify]],
                                   @"收文时间":[self timeStampToDate:[ValidateUtils validateNull:model.fileReceiveDate]],
                                   @"是否归档":[ValidateUtils validateNull:model.isFiling.integerValue == 0 ? @"未归档" : @"已归档"],
                                   @"备注":[ValidateUtils validateNull:model.fileRemark]
                                   }];
    }
    // 文件管理器
    NSFileManager *fileManager = [[NSFileManager alloc]init];
    // 文件路径
    NSString *path = NSHomeDirectory();
    // 在Documents下创建文件夹
    BOOL isDir = FALSE;
    BOOL isDirExist = [fileManager fileExistsAtPath:[NSString stringWithFormat:@"%@/Documents/export",path] isDirectory:&isDir];
    if(!(isDirExist && isDir)) {
        BOOL bCreateDir = [fileManager createDirectoryAtPath:[NSString stringWithFormat:@"%@/Documents/export",path] withIntermediateDirectories:YES attributes:nil error:nil];
        if(!bCreateDir){
            NSLog(@"创建文件夹失败！");
        }
        NSLog(@"创建文件夹成功，文件路径%@",[NSString stringWithFormat:@"%@/Documents/export",path]);
    }
    NSDateFormatter *df2 = [[NSDateFormatter alloc] init];//格式化
    [df2 setDateFormat:@"yyyyMMddHHmmss"];
    NSDate *date = [NSDate date];
    NSString *filePath = [path stringByAppendingPathComponent:[NSString stringWithFormat:@"/Documents/export/%@来文登记薄.xls",[df2 stringFromDate:date]]];
    NSLog(@"文件路径：\n%@",filePath);
    lxw_workbook  *workbook  = workbook_new([filePath UTF8String]);// 创建新xlsx文件，路径需要转成c字符串
    lxw_worksheet *worksheet = workbook_add_worksheet(workbook, NULL);// 创建sheet
    
    [xlsDataMuArrM.copy enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        NSDictionary *aDic=obj;
        NSString *fileTitle=aDic[@"文件标题"];
        NSString *fileNum=aDic[@"原文编号"];
        NSString *fileCode=aDic[@"字号"];
        NSString *fileCompany=aDic[@"来文单位"];
        NSString *fileClassify=aDic[@"收文分类"];
        NSString *fileReceiveDate=aDic[@"收文时间"];
        NSString *isFiling=aDic[@"是否归档"];
        NSString *fileRemark=aDic[@"备注"];
        
        uint32_t lxw_row_t = (uint32_t)idx;
        
        worksheet_write_string(worksheet, lxw_row_t, 0, [fileTitle UTF8String], NULL);
        worksheet_write_string(worksheet, lxw_row_t, 1, [fileNum UTF8String], NULL);
        worksheet_write_string(worksheet, lxw_row_t, 2, [fileCode UTF8String], NULL);
        worksheet_write_string(worksheet, lxw_row_t, 3, [fileCompany UTF8String], NULL);
        worksheet_write_string(worksheet, lxw_row_t, 4, [fileClassify UTF8String], NULL);
        worksheet_write_string(worksheet, lxw_row_t, 5, [fileReceiveDate UTF8String], NULL);
        worksheet_write_string(worksheet, lxw_row_t, 6, [isFiling UTF8String], NULL);
        worksheet_write_string(worksheet, lxw_row_t, 7, [fileRemark UTF8String], NULL);
    }];
    //关闭，保存文件
    workbook_close(workbook);
     */
    
    
    // 创建存放XLS文件数据的数组
    NSMutableArray  *xlsDataMuArr = [[NSMutableArray alloc] init];
    // 第一行内容
    [xlsDataMuArr addObject:@"文件标题"];
    [xlsDataMuArr addObject:@"原文编号"];
    [xlsDataMuArr addObject:@"字号"];
    [xlsDataMuArr addObject:@"来文单位"];
    [xlsDataMuArr addObject:@"收文分类"];
    [xlsDataMuArr addObject:@"收文时间"];
    [xlsDataMuArr addObject:@"是否归档"];
    [xlsDataMuArr addObject:@"备注"];
    // 100行数据
    for (int i = 0; i < array.count; i ++) {
        LSLevinBookListModel *model = self.dataArrayM[i];
        [xlsDataMuArr addObject:[ValidateUtils validateNull:model.fileTitle]];
        [xlsDataMuArr addObject:[NSString stringWithFormat:@"’%@",[ValidateUtils validateNull:model.fileNum]]];
        [xlsDataMuArr addObject:[ValidateUtils validateNull:model.fileCode]];
        [xlsDataMuArr addObject:[ValidateUtils validateNull:model.fileCompany]];
        [xlsDataMuArr addObject:[ValidateUtils validateNull:[[ValidateUtils validateNull:self.fileClassifyDict[model.fileClassify]] isEqualToString:@""] ? model.fileClassify : self.fileClassifyDict[model.fileClassify]]];
        [xlsDataMuArr addObject:[self timeStampToDate:[ValidateUtils validateNull:model.fileReceiveDate]]];
        [xlsDataMuArr addObject:[ValidateUtils validateNull:model.isFiling.integerValue == 0 ? @"未归档" : @"已归档"]];
        [xlsDataMuArr addObject:[ValidateUtils validateNull:model.fileRemark]];
    }
    
    // 文件保存的路径
    NSFileManager *fileManager = [[NSFileManager alloc]init];
    // 文件路径
    NSString *path = NSHomeDirectory();
    // 在Documents下创建文件夹
    BOOL isDir = FALSE;
    BOOL isDirExist = [fileManager fileExistsAtPath:[NSString stringWithFormat:@"%@/Documents/export",path] isDirectory:&isDir];
    if(!(isDirExist && isDir)) {
        BOOL bCreateDir = [fileManager createDirectoryAtPath:[NSString stringWithFormat:@"%@/Documents/export",path] withIntermediateDirectories:YES attributes:nil error:nil];
        if(!bCreateDir){
            NSLog(@"创建文件夹失败！");
        }
        NSLog(@"创建文件夹成功，文件路径%@",[NSString stringWithFormat:@"%@/Documents/export",path]);
    }
    NSDateFormatter *df2 = [[NSDateFormatter alloc] init];//格式化
    [df2 setDateFormat:@"yyyyMMddHHmmss"];
    NSDate *date = [NSDate date];
    NSString *filename = [path stringByAppendingPathComponent:[NSString stringWithFormat:@"/Documents/export/%@.xlsx",[df2 stringFromDate:date]]];//来文登记薄
    NSLog(@"filepath:%@",filename);
    lxw_workbook  *workbook  = workbook_new([filename UTF8String]);// 创建新xlsx文件，路径需要转成c字符串
    lxw_worksheet *worksheet = workbook_add_worksheet(workbook, NULL);// 创建sheet
    
    [xlsDataMuArr enumerateObjectsUsingBlock:^(NSString *  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        int index = idx % 8;//列
        int page = (int)idx / 8;//行
//        if (index == 1 && page > 0) {
//            worksheet_write_number(worksheet, page, index, obj.intValue, NULL);
//        } else {
//            worksheet_write_string(worksheet, page, index, [obj cStringUsingEncoding:NSUTF8StringEncoding], NULL);
//        }
        worksheet_write_string(worksheet, page, index, [obj cStringUsingEncoding:NSUTF8StringEncoding], NULL);
    }];
    
    //关闭，保存文件
    workbook_close(workbook);
    [MBProgressHUD showSuccessMessage:@"导出完成"];
//    // 把数组拼接成字符串，连接符是 \t（功能同键盘上的tab键）
//    NSString *fileContent = [xlsDataMuArr componentsJoinedByString:@"\t"];
//    // 字符串转换为可变字符串，方便改变某些字符
//    NSMutableString *muStr = [fileContent mutableCopy];
//    // 新建一个可变数组，存储每行最后一个\t的下标（以便改为\n）
//    NSMutableArray *subMuArr = [NSMutableArray array];
//    for (int i = 0; i < muStr.length; i ++) {
//        NSRange range = [muStr rangeOfString:@"\t" options:NSBackwardsSearch range:NSMakeRange(i, 1)];
//        if (range.length == 1) {
//            [subMuArr addObject:@(range.location)];
//        }
//    }
//    // 替换末尾\t
//    for (NSUInteger i = 0; i < subMuArr.count; i ++) {
//#pragma mark - 下面的8是列数，根据需求修改
//        if ( i > 0 && (i%8 == 0) ) {
//            [muStr replaceCharactersInRange:NSMakeRange([[subMuArr objectAtIndex:i-1] intValue], 1) withString:@"\n"];
//        }
//    }
//    // 文件管理器
//    NSFileManager *fileManager = [[NSFileManager alloc]init];
//    //使用UTF16才能显示汉字；如果显示为#######是因为格子宽度不够，拉开即可
//    NSData *fileData = [muStr dataUsingEncoding:NSUTF16StringEncoding];
//    // 文件路径
//    NSString *path = NSHomeDirectory();
//    // 在Documents下创建文件夹
//    BOOL isDir = FALSE;
//    BOOL isDirExist = [fileManager fileExistsAtPath:[NSString stringWithFormat:@"%@/Documents/export",path] isDirectory:&isDir];
//    if(!(isDirExist && isDir)) {
//        BOOL bCreateDir = [fileManager createDirectoryAtPath:[NSString stringWithFormat:@"%@/Documents/export",path] withIntermediateDirectories:YES attributes:nil error:nil];
//        if(!bCreateDir){
//            NSLog(@"创建文件夹失败！");
//        }
//        NSLog(@"创建文件夹成功，文件路径%@",[NSString stringWithFormat:@"%@/Documents/export",path]);
//    }
//    NSDateFormatter *df2 = [[NSDateFormatter alloc] init];//格式化
//    [df2 setDateFormat:@"yyyyMMddHHmmss"];
//    NSDate *date = [NSDate date];
//    NSString *filePath = [path stringByAppendingPathComponent:[NSString stringWithFormat:@"/Documents/export/%@.xls",[df2 stringFromDate:date]]];//来文登记薄
//    NSLog(@"文件路径：\n%@",filePath);
//    // 生成xls文件
//    BOOL exportSecceed = [fileManager createFileAtPath:filePath contents:fileData attributes:nil];
//    if (exportSecceed) {
//        [MBProgressHUD showSuccessMessage:@"导出成功"];
//    } else {
//        [MBProgressHUD showErrorMessage:@"导出失败"];
//    }
}

- (NSString *)timeStampToDate:(NSString *)timeStampString {
    // iOS 生成的时间戳是10位
    if (![[ValidateUtils validateNull:timeStampString] isEqualToString:@""] && !([ValidateUtils validateNull:timeStampString].integerValue == 0)) {
        NSTimeInterval interval    =[timeStampString doubleValue] / 1000.0;
        NSDate *date               = [NSDate dateWithTimeIntervalSince1970:interval];
        NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
        [formatter setDateFormat:@"yyyy-MM-dd"];
        return [formatter stringFromDate: date];
    }
    return @"";
}

- (void)loadData {
    self.page = 1;
    MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.view animated:true];
    NSDictionary *param = @{};
    if ([self.fileClassifyString isEqualToString:@""]) {
        param = @{@"token":[UserInfoModel sharedInstance].token,
                  @"page":[NSString stringWithFormat:@"%d",self.page],
                  @"rows":[NSString stringWithFormat:@"%d",rows]
                  };
    } else {
        param = @{@"token":[UserInfoModel sharedInstance].token,
                  @"page":[NSString stringWithFormat:@"%d",self.page],
                  @"rows":[NSString stringWithFormat:@"%d",rows],
                  @"fileClassify":self.fileClassifyString
                  };
    }
    [NetworkUtils requestNOHandleWithMethod:@"POST" URL:LevinBookList param:param completionHandler:^(id responseObject, NSError *connectionError) {
        [hud hideAnimated:true];
        if (!connectionError) {
            self.tableView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(loadMoreData)];
            [self.tableView.mj_header endRefreshing];
            NSNumber *status = [responseObject objectForKey:@"status"];
            if (status.integerValue == 200) {
                NSArray *dataArray = [responseObject objectForKey:@"data"];
                if (dataArray && dataArray.count > 0) {
                    [self.dataArrayM removeAllObjects];
                    [self.nodataView removeFromSuperview];
                    [self.networkErrorView removeFromSuperview];
                    for (NSDictionary *dict in dataArray) {
                        LSLevinBookListModel *model = [LSLevinBookListModel mj_objectWithKeyValues:dict];
                        if (model) {
                            [self.dataArrayM addObject:model];
                        }
                    }
                    if (self.dataArrayM.count < self.page*rows) {
                        [self.tableView.mj_footer endRefreshingWithNoMoreData];
                    }
                } else {
                    [self.networkErrorView removeFromSuperview];
                    [self.tableView addSubview:self.nodataView];
                }
                [self.tableView reloadData];
            } else {
                [self.nodataView removeFromSuperview];
                [self.tableView addSubview:self.networkErrorView];
                self.networkErrorView.tipText = [ValidateUtils validateNull:responseObject[@"message"]];
            }
        } else {
            [self.nodataView removeFromSuperview];
            [self.tableView addSubview:self.networkErrorView];
            self.networkErrorView.tipText = [NSString stringWithFormat:@"%@",connectionError.localizedDescription];
        }
    }];
}

- (void)loadMoreData {
    self.page++;
    MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.view animated:true];
    NSDictionary *param = @{};
    if ([self.fileClassifyString isEqualToString:@""]) {
        param = @{@"token":[UserInfoModel sharedInstance].token,
                  @"page":[NSString stringWithFormat:@"%d",self.page],
                  @"rows":[NSString stringWithFormat:@"%d",rows]
                  };
    } else {
        param = @{@"token":[UserInfoModel sharedInstance].token,
                  @"page":[NSString stringWithFormat:@"%d",self.page],
                  @"rows":[NSString stringWithFormat:@"%d",rows],
                  @"fileClassify":self.fileClassifyString
                  };
    }
    [NetworkUtils requestNOHandleWithMethod:@"POST" URL:LevinBookList param:param completionHandler:^(id responseObject, NSError *connectionError) {
        [hud hideAnimated:true];
        if (!connectionError) {
            NSNumber *status = [responseObject objectForKey:@"status"];
            NSNumber *totalCount = responseObject[@"totalNum"];
            if (status.integerValue == 200) {
                NSArray *dataArray = [responseObject objectForKey:@"data"];
                if (dataArray > 0) {
                    for (NSDictionary *dict in dataArray) {
                        LSLevinBookListModel *model = [LSLevinBookListModel mj_objectWithKeyValues:dict];
                        if (model) {
                            [self.dataArrayM addObject:model];
                        }
                    }
                    if (self.dataArrayM.count >= totalCount.intValue) {
                        [self.tableView.mj_footer endRefreshingWithNoMoreData];
                    } else {
                        [self.tableView.mj_footer endRefreshing];
                    }
                    [self.tableView reloadData];
                }
            } else {
                self.page--;
                [self.tableView.mj_footer endRefreshingWithNoMoreData];
            }
        } else {
            self.page--;
            [self.tableView.mj_footer endRefreshing];
            [MBProgressHUD showTipMessageInWindow:connectionError.localizedDescription];
        }
    }];
}

- (void)createHeader {
    UIView *headerSelectView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, ScreenWidth, headerSelectViewHeight)];
    headerSelectView.backgroundColor = UIColor.whiteColor;
    headerSelectView.layer.shadowRadius = 5;
    headerSelectView.layer.shadowColor = hexColor(cccccc).CGColor;
    
    UITextField *selectTF = [[UITextField alloc] initWithFrame:CGRectMake(12, 12, ScreenWidth-(headerSelectViewHeight-8)-(headerSelectViewHeight-8)-12-12-12, 50-4-12)];
    selectTF.backgroundColor = hexColor(eeeeee);
    self.selectTF = selectTF;
    selectTF.delegate = self;
    selectTF.textAlignment = NSTextAlignmentCenter;
    selectTF.text = @"请选择";
    selectTF.font = [UIFont systemFontOfSize:15];
    [headerSelectView addSubview:selectTF];
    
    UIButton *downSelectButton = [[UIButton alloc] initWithFrame:CGRectMake(ScreenWidth-(headerSelectViewHeight-8)-(headerSelectViewHeight-8)-12-12, 12, headerSelectViewHeight-4-12, headerSelectViewHeight-4-12)];
    downSelectButton.layer.cornerRadius = (headerSelectViewHeight-8)/2;
    downSelectButton.layer.masksToBounds = true;
    [downSelectButton addTarget:self action:@selector(showDownSelectView) forControlEvents:UIControlEventTouchUpInside];
    [downSelectButton setImage:[UIImage imageNamed:@"xiala"] forState:UIControlStateNormal];
    [headerSelectView addSubview:downSelectButton];
    
    UIButton *searchButton = [[UIButton alloc] initWithFrame:CGRectMake(ScreenWidth-12-50, 12, 50, headerSelectViewHeight-4-12)];
    searchButton.backgroundColor = NAV_COLOR;
    searchButton.layer.cornerRadius = 5;
    searchButton.layer.masksToBounds = true;
    [searchButton setTitle:@"搜索" forState:UIControlStateNormal];
    [searchButton setTitleColor:UIColor.whiteColor forState:UIControlStateNormal];
    searchButton.titleLabel.font = [UIFont systemFontOfSize:15];
    [searchButton addTarget:self action:@selector(loadData) forControlEvents:UIControlEventTouchUpInside];
    [headerSelectView addSubview:searchButton];
    
    [self.view addSubview:headerSelectView];
}

- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField {
    [self showDownSelectView];
    return false;
}

- (void)showDownSelectView {
    UIView *downSelectView = [[UIView alloc] initWithFrame:CGRectMake(12, SafeAreaTopHeight+12, CGRectGetWidth(self.selectTF.frame), (50-4-12)*self.fileClassifyReverseDict.count)];
    self.downSelectView = downSelectView;
    downSelectView.layer.shadowColor = UIColor.blackColor.CGColor;
    downSelectView.layer.shadowOffset = CGSizeZero;
    downSelectView.layer.shadowRadius = 5;
    downSelectView.layer.shadowOpacity = 0.8;
    downSelectView.backgroundColor = UIColor.whiteColor;
    for (int i = 0; i < self.fileClassifyReverseArray.count; i++) {
        NSString *key = self.fileClassifyReverseArray[i];
        UIButton *selectButton = [[UIButton alloc] initWithFrame:CGRectMake(0, i*(50-4-12), CGRectGetWidth(self.selectTF.frame), (50-4-12))];
        [selectButton setTitle:key forState:UIControlStateNormal];
        [selectButton setTitleColor:hexColor(333333) forState:UIControlStateNormal];
        selectButton.titleLabel.font = [UIFont systemFontOfSize:15];
        [selectButton addTarget:self action:@selector(selectButtonClick:) forControlEvents:UIControlEventTouchUpInside];
        [downSelectView addSubview:selectButton];
    }
    UIWindow *window = [UIApplication sharedApplication].keyWindow;
    UIView *downSelectViewBackAlphaView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, ScreenWidth, ScreenHeight)];
    self.downSelectViewBackAlphaView = downSelectViewBackAlphaView;
    downSelectViewBackAlphaView.backgroundColor = UIColor.clearColor;
    downSelectViewBackAlphaView.userInteractionEnabled = true;
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(downSelectViewBackAlphaViewTapped)];
    [downSelectViewBackAlphaView addGestureRecognizer:tap];
    [window addSubview:downSelectViewBackAlphaView];
    [window addSubview:downSelectView];
}

- (void)selectButtonClick:(UIButton *)selectButton {
    self.selectTF.text = selectButton.titleLabel.text;
    self.fileClassifyString = self.fileClassifyReverseDict[self.selectTF.text];
    [self downSelectViewBackAlphaViewTapped];
}

- (void)downSelectViewBackAlphaViewTapped {
    [self.downSelectView removeFromSuperview];
    [self.downSelectViewBackAlphaView removeFromSuperview];
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return self.dataArrayM.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return 1;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    LSLevinBookListViewCell *cell = [tableView dequeueReusableCellWithIdentifier:LSLevinBookListViewCellID forIndexPath:indexPath];
    cell.model = self.dataArrayM[indexPath.section];
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:true];
    LSLevinBookDetailViewController *levinBookDetailVC = [[LSLevinBookDetailViewController alloc] init];
    levinBookDetailVC.model = self.dataArrayM[indexPath.section];
    [self.navigationController pushViewController:levinBookDetailVC animated:true];
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return LSLevinBookListViewCellHeight;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    UIView *sectionHeaderView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, ScreenWidth, 8)];
    sectionHeaderView.backgroundColor = hexColor(eeeeee);
    return sectionHeaderView;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return 8;
}

-(NSArray<UITableViewRowAction*>*)tableView:(UITableView *)tableView editActionsForRowAtIndexPath:(NSIndexPath *)indexPath {
    NSDictionary *dataDict = self.dataArrayM[indexPath.section];
    WS
    UITableViewRowAction *rowAction = [UITableViewRowAction rowActionWithStyle:UITableViewRowActionStyleNormal title:@"导出" handler:^(UITableViewRowAction * _Nonnull action, NSIndexPath * _Nonnull indexPath) {
        [weakSelf createXLSFileWithArray:@[dataDict]];
    }];
    rowAction.backgroundColor = NAV_COLOR;
    NSArray *arr = @[rowAction];
    return arr;
}

- (UITableView *)tableView {
    if (!_tableView) {
        _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, headerSelectViewHeight, ScreenWidth, ScreenHeight-SafeAreaTopHeight-headerSelectViewHeight)];
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.tableFooterView = [UIView new];
        _tableView.backgroundColor = hexColor(eeeeee);
        [_tableView registerClass:LSLevinBookListViewCell.class forCellReuseIdentifier:LSLevinBookListViewCellID];
    }
    return _tableView;
}

- (NSMutableArray *)dataArrayM {
    if (!_dataArrayM) {
        _dataArrayM = [[NSMutableArray alloc] init];
    }
    return _dataArrayM;
}

- (NZKNoDataView *)nodataView {
    if (!_nodataView) {
        _nodataView = [[NZKNoDataView alloc] initWithFrame:CGRectMake(0, headerSelectViewHeight, ScreenWidth, ScreenHeight-SafeAreaTopHeight-headerSelectViewHeight) withTip:@"暂无相关信息" andButtonText:nil];
    }
    return _nodataView;
}

- (NZKNetworkErrorView *)networkErrorView {
    if (!_networkErrorView) {
        WS
        _networkErrorView = [[NZKNetworkErrorView alloc] initWithFrame:CGRectMake(0, headerSelectViewHeight, ScreenWidth, ScreenHeight-SafeAreaTopHeight-headerSelectViewHeight) withRefreshBlock:^{
            [weakSelf loadData];
        }];
    }
    return _networkErrorView;
}

- (NSDictionary *)fileClassifyDict {
    if (!_fileClassifyDict) {
        _fileClassifyDict = @{@"central":@"中央文件",
                              @"autonomousRegion":@"自治区文件",
                              @"MuniGovernment":@"市委市政府文件",
                              @"bureau":@"本局文件",
                              @"MuniDepartments":@"市直相关部门文件"
                              };
    }
    return _fileClassifyDict;
}

- (NSArray *)fileClassifyReverseArray {
    if (!_fileClassifyReverseArray) {
        _fileClassifyReverseArray = @[@"请选择",
                                      @"中央文件",
                                      @"自治区文件",
                                      @"市委市政府文件",
                                      @"本局文件",
                                      @"市直相关部门文件"];
    }
    return _fileClassifyReverseArray;
}

- (NSDictionary *)fileClassifyReverseDict {
    if (!_fileClassifyReverseDict) {
        _fileClassifyReverseDict = @{@"请选择":@"",
                                     @"中央文件":@"central",
                                     @"自治区文件":@"autonomousRegion",
                                     @"市委市政府文件":@"MuniGovernment",
                                     @"本局文件":@"bureau",
                                     @"市直相关部门文件":@"MuniDepartments"
                              };
    }
    return _fileClassifyReverseDict;
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
